package com.pinionoffice.oa

import com.pinionoffice.User
import org.apache.commons.lang.builder.HashCodeBuilder

class DepUser implements Serializable {
    User user
    Department department

    boolean equals(other) {
        if (!(other instanceof DepUser)) {
            return false
        }

        other.user?.id == user?.id &&
                other.role?.id == role?.id
    }

    int hashCode() {
        def builder = new HashCodeBuilder()
        if (user) builder.append(user.id)
        if (department) builder.append(department.id)
        builder.toHashCode()
    }

    static DepUser get(long userId, long roleId) {
        find 'from UserRole where user.id=:userId and role.id=:roleId',
                [userId: userId, roleId: roleId]
    }

    static DepUser create(User user, Department role, boolean flush = false) {
        new DepUser(user: user, role: role).save(flush: flush, insert: true)
    }

    static boolean remove(User user, Department role, boolean flush = false) {
        DepUser instance = DepUser.findByUserAndDepartment(user, role)
        if (!instance) {
            return false
        }

        instance.delete(flush: flush)
        true
    }

    static void removeAll(User user) {
        executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
    }

    static void removeAll(Department role) {
        executeUpdate 'DELETE FROM UserRole WHERE role=:role', [role: role]
    }

    static mapping = {
        id composite: ['department', 'user']
        version false
    }
}
